package br.com.android.financas;

import java.io.File;
import java.io.IOException;

import org.joda.time.DateTime;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.activities.Home;
import br.com.android.financas.adapter.FileAdapter;

public class BackUp extends AsyncTask<String, String, Boolean> {

	private Activity activity;
	private ProgressDialog progress;
	private Spinner campoArquivo;
	private String message;
	private boolean restore=false;

	public BackUp(Activity activity) {
		this.activity=activity;
	}


	public File makeBackup() throws IOException, NameNotFoundException{

	    final String inFileName =  activity.getApplicationContext().getPackageManager().getPackageInfo(activity.getPackageName(), 0).applicationInfo.dataDir+"/databases/financas.db";

	    File dir = new File(Environment.getExternalStorageDirectory() + "/Financas");
	    if(!dir.exists()) {
	        if(!dir.mkdir()){
	        	throw new IOException("Impossivel criar diretorio!");
	        }
	    }

	    File source = new File(inFileName);
	    String outFileName=dir.getAbsolutePath()+"/backup."+new DateTime().toString("dd_MM_yyyy");
	    File dest=new File(outFileName);

	    Utils.copyFile(source, dest,this);


	    return dest;
	}

	public void backup(){
		execute("backup");
	}

	public void restaurar(){
		File dir = new File(Environment.getExternalStorageDirectory() + "/Financas");

		File[] listOfFiles = dir.listFiles();

		FileAdapter adapter=new FileAdapter(activity, R.layout.sherlock_spinner_item, listOfFiles);


		LayoutInflater factory = LayoutInflater.from(activity);
	    View layout = factory.inflate(R.layout.restaurar_screen, null);
		campoArquivo = (Spinner) layout.findViewById(R.restaurar.arquivo);
		campoArquivo.setAdapter(adapter);

		AlertDialog.Builder builder = new AlertDialog.Builder(activity);

		builder.setView(layout);
		builder.setTitle("Escolha o que restaurar");
		builder.setCancelable(false);
		builder.setPositiveButton("Restaurar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						execute("restore");
					}
				});
		builder.setNegativeButton("Cancelar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private void makeRestore(File source) throws NameNotFoundException, IOException{

		 	String outFileName =  activity.getApplicationContext().getPackageManager().getPackageInfo(activity.getPackageName(), 0).applicationInfo.dataDir+"/databases/financas.db";

		 	File dbatual=new File(outFileName);

		 	//cria backup
		 	File tmp=new File(outFileName+"_tmp");
		 	Utils.copyFile(dbatual, tmp,this);


		 	try {
				Utils.copyFile(source, dbatual,this);

				tmp.delete();
			} catch (IOException e) {
				if(tmp.exists()){
					Utils.copyFile(tmp, dbatual,this);
					tmp.delete();
				}
			}

	}


	@Override
	protected Boolean doInBackground(String... paramss) {
		try {

			if(paramss[0]=="backup"){
				makeBackup();
				message="Backup criado com sucesso!";
			}else{
				makeRestore((File) campoArquivo.getSelectedItem());
				message="Restaurado com sucesso!";
				restore=true;
			}

		} catch (Exception e) {
			message=e.getMessage();
			return false;
		}
		return true;
	}

	  @Override
      protected void onPreExecute() {
		  progress = new ProgressDialog(activity);
          //Cria novo um ProgressDialogo e exibe
          progress.setMessage("Aguarde...");
          progress.show();
      }

	  @Override
      protected void onPostExecute(Boolean result) {
		  if(result && restore)
			  ( (Home) activity).onChange(true);

		  //Cancela progressDialogo
          progress.dismiss();
          Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
      }

      @Override
      protected void onProgressUpdate(String... values) {
          //Atualiza mensagem
    	  if(progress!=null)
    		  progress.setMessage(values[0]);
      }

      public void setProgress(Integer p, Long size){
    	  publishProgress("Aguarde "+p+"/"+size);
      }

}
